package com.demo.las.controller;

import com.demo.las.entity.AffairCatalog;
import com.demo.las.service.AffairCatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/affair-catalog")
@CrossOrigin(origins = "*")
public class AffairCatalogController {

    @Autowired
    private AffairCatalogService affairCatalogService;

    @GetMapping
    public List<AffairCatalog> list(@RequestParam(value = "categoryCode", required = false) Integer categoryCode) {
        if (categoryCode != null) {
            return affairCatalogService.getActiveByCategory(categoryCode);
        }
        return affairCatalogService.getAllActive();
    }

    // 新增：按ID查询
    @GetMapping("/{id}")
    public ResponseEntity<AffairCatalog> getById(@PathVariable Long id) {
        Optional<AffairCatalog> item = affairCatalogService.getById(id);
        return item.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public AffairCatalog add(@RequestBody AffairCatalog item) {
        return affairCatalogService.addItem(item);
    }

    // 新增：更新库项
    @PutMapping("/{id}")
    public AffairCatalog update(@PathVariable Long id, @RequestBody AffairCatalog item) {
        item.setId(id);
        return affairCatalogService.updateItem(item);
    }

    // 新增：删除库项
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        affairCatalogService.deleteItem(id);
        return ResponseEntity.noContent().build();
    }
}